package com.zzqstart.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzqstart.commonutils.JwtUtils;
import com.zzqstart.commonutils.MD5;
import com.zzqstart.servicebase.exceptionhandler.CateException;
import com.zzqstart.userservice.entity.UcenterMember;
import com.zzqstart.userservice.entity.vo.QueryChef;
import com.zzqstart.userservice.entity.vo.RegisterVo;
import com.zzqstart.userservice.mapper.UcenterMemberMapper;
import com.zzqstart.userservice.service.UcenterMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-03-06
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String checkUser(UcenterMember ucenterMember) {
        if (ucenterMember == null) {
            throw new CateException(20001, "用户输入信息为空");
        }

        String mobile = ucenterMember.getMobile();
        String password = ucenterMember.getPassword();

        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new CateException(20001, "请输入手机号或密码");
        }

        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        UcenterMember memberBD = baseMapper.selectOne(wrapper);

        if (memberBD == null) {
            throw new CateException(20001, "用户不存在");
        }

        // 数据库密码
        String memberPassword = memberBD.getPassword();
        // 用户输入密码加密
        String MD5Password = MD5.encrypt(password);

        if (!memberPassword.equals(MD5Password)) {
            throw new CateException(20001, "密码错误,请重新输入");
        }

        // 是否禁用
        if (memberBD.getIsDisabled()) {
            throw new CateException(20001, "账号被禁用");
        }

        String id = memberBD.getId();
        String nickname = memberBD.getNickname();
        String token = JwtUtils.getJwtToken(id, nickname);

        return token;
    }

    @Override
    public Boolean register(RegisterVo registerVo) {
        if (registerVo == null) {
            throw new CateException(20001, "不能为空");
        }

        String mobile = registerVo.getMobile();
        String nickname = registerVo.getNickname();
        String code = registerVo.getCode();
        String password = registerVo.getPassword();

        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)) {
            throw new CateException(20001, "请输入正确信息");
        }

        String codeRedis = redisTemplate.opsForValue().get(mobile);
        if (!code.equals(codeRedis)) {
            throw new CateException(20001, "验证码错误");
        }

        // 是否存在该手机号码
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new CateException(20001, "该手机号码已注册");
        }

        UcenterMember member = new UcenterMember();
        member.setNickname(nickname);
        member.setIsDisabled(false);
        member.setMobile(mobile);
        member.setPassword(MD5.encrypt(password));

        int insert = baseMapper.insert(member);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public UcenterMember getMemberById(String memberId) {
        UcenterMember member = baseMapper.selectById(memberId);
        member.setPassword("");
        return member;
    }

    @Override
    public Map<String, Object> getAllChef(Long page, Long limit, QueryChef query) {
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        // 手写sql
//        if (!StringUtils.isEmpty(recipeCounte) && recipeCounte == 1){
//            Long newPage = (page-1)*limit;
//            List<UcenterMember> list = baseMapper.getMemberOrderRecipe(newPage,limit);
//            map.put("list",list);
//            map.put("total",list.size());
//            return map;
//        }
        Page<UcenterMember> pageInfo = new Page<>(page, limit);
//        wrapper.eq("is_deleted", 0);
        wrapper.select("id,nickname,avatar,sign,create_time,is_chef");

        if (!StringUtils.isEmpty(query)) {
            if (!StringUtils.isEmpty(query.getRecipeCounte()) && query.getRecipeCounte()) {
                    wrapper.last("WHERE id IN (SELECT publisher_id id FROM cate_recipe " +
                            "GROUP BY publisher_id ORDER BY COUNT(1) ASC)");
            }


            if (!StringUtils.isEmpty(query.getIsChef()) && query.getIsChef()) {
                    wrapper.eq("is_chef",1);
            }

            if (!StringUtils.isEmpty(query.getLatest()) && query.getLatest()) {
                wrapper.orderByDesc("create_time");
            }
        }

        baseMapper.selectPage(pageInfo, wrapper);

        List<UcenterMember> list = pageInfo.getRecords();
        map.put("total", pageInfo.getTotal());
        map.put("list", list);

        return map;
    }

    @Override
    public Map<String, Object> allMemberPage(long current, long limit, UcenterMember member) {
        Page<UcenterMember> page = new Page<>(current,limit);
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();

        String nickname = member.getNickname();
        Integer isChef = member.getIsChef();
        Integer kitchenAge = member.getKitchenAge();
        String mobile = member.getMobile();
        Integer sex = member.getSex();
        Date createTime = member.getCreateTime();
        Boolean isDisabled = member.getIsDisabled();
        Boolean isDeleted = member.getIsDeleted();
        if (!StringUtils.isEmpty(member)){
            if (!StringUtils.isEmpty(nickname)){
                wrapper.like("nickname",nickname);
            }

            if (!StringUtils.isEmpty(isChef)){
                wrapper.eq("is_chef",isChef);
            }
            if (!StringUtils.isEmpty(kitchenAge)){
                wrapper.eq("kitchen_age",kitchenAge);
            }
            if (!StringUtils.isEmpty(mobile)){
                wrapper.eq("mobile",mobile);
            }
            if (!StringUtils.isEmpty(sex)){
                wrapper.eq("sex",sex);
            }
            if (!StringUtils.isEmpty(createTime)){
                wrapper.lt("create_time",createTime);
            }
            if (!StringUtils.isEmpty(isDisabled)){
                wrapper.eq("is_disabled",isDisabled);
            }
            if (!StringUtils.isEmpty(isDeleted)){
                wrapper.eq("is_deleted",isDeleted);
            }
        }

        baseMapper.selectPage(page,wrapper);

        List<UcenterMember> list = page.getRecords();
        long total = page.getTotal();
        long size = page.getSize();

        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",total);
        map.put("size",size);

        return map;
    }

}
